<template>
  <div class="parent">
    <div class="child">
      <el-form :model="form" label-width="auto" style="max-width: 600px">
        <el-form-item label="用户名">
          <el-input v-model="form.UserName" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.Password" show-password />
        </el-form-item>
        <el-form-item label="验证码">
          <el-input v-model="form.vcode" style="width: 150px;" />
          <div class="captcha" @click="refreshCaptcha">
            <canvas ref="canvas" :width="width" :height="height"></canvas>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">登录</el-button>
          <el-button type="primary" @click="onSubmits">测试登录</el-button>
          <!-- <el-button>Cancel</el-button> -->
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios';
import { useRouter } from 'vue-router';
import { useCounterStore } from '@/stores/counter';

const store = useCounterStore();
const router = useRouter();

//#region 验证码
// 定义组件接收的属性
const props = defineProps({
  width: {
    type: Number,
    default: 120
  },
  height: {
    type: Number,
    default: 40
  },
  length: {
    type: Number,
    default: 4
  }
});

// 获取 canvas 元素的引用
const canvas = ref(null);
// 存储当前验证码文本
const captchaText = ref('');

// 生成随机验证码字符串
const generateCaptcha = () => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let text = '';
  for (let i = 0; i < props.length; i++) {
    text += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  captchaText.value = text;
  return text;
};

// 生成随机颜色
const getRandomColor = () => {
  const r = Math.floor(Math.random() * 256);
  const g = Math.floor(Math.random() * 256);
  const b = Math.floor(Math.random() * 256);
  return `rgb(${r},${g},${b})`;
};

// 绘制验证码到 canvas 上
const drawCaptcha = () => {
  const ctx = canvas.value.getContext('2d');
  // 清空画布
  ctx.clearRect(0, 0, props.width, props.height);
  // 设置字体和颜色
  ctx.font = '30px Arial';
  ctx.fillStyle = getRandomColor();

  const captcha = generateCaptcha();
  for (let i = 0; i < captcha.length; i++) {
    const x = (props.width / (props.length + 1)) * (i + 1);
    const y = props.height / 2 + Math.random() * 10 - 5;
    // 保存当前绘图状态
    ctx.save();
    // 平移和旋转文本
    ctx.translate(x, y);
    ctx.rotate((Math.random() - 0.5) * (Math.PI / 4));
    // 绘制单个字符
    ctx.fillText(captcha[i], 0, 0);
    // 恢复之前保存的绘图状态
    ctx.restore();
  }

  // 绘制干扰线
  for (let i = 0; i < 5; i++) {
    ctx.beginPath();
    ctx.strokeStyle = getRandomColor();
    ctx.moveTo(Math.random() * props.width, Math.random() * props.height);
    ctx.lineTo(Math.random() * props.width, Math.random() * props.height);
    ctx.stroke();
  }
};

// 刷新验证码
const refreshCaptcha = () => {
  drawCaptcha();
};

// 组件挂载后绘制验证码
onMounted(() => {
  drawCaptcha();
});

// 向外暴露获取验证码文本的方法
const getCaptchaText = () => {
  return captchaText.value;
};

defineExpose({
  getCaptchaText
});
//#endregion


//#region  登录
const form = reactive({
  UserName: '',
  Password: '',
  vcode: '' //验证码
})

const onSubmit = () => {
  //验证码验证
  if (form.vcode.toLocaleLowerCase() != captchaText.value.toLocaleLowerCase()) {
    console.log(captchaText.value)
    ElMessage.error("验证码不匹配");
    return;
  }
  axios.get("https://localhost:7174/api/Message/Login", {
    params: {
      UserName: form.UserName,
      Password: form.Password
    }
  }).then(res => {
    if (res.data.code == 202) {
      ElMessage.success(res.data.msg)
      store.ccstore.nickName = res.data.data.nickName
      store.ccstore.userId = res.data.data.userId
      store.ccstore.userName = res.data.data.userName
      store.ccstore.depId = res.data.data.depId
      store.ccstore.levelRoleId = res.data.data.levelRoleId
      router.push("/MianView")
      console.log(res.data.data.nickName)
    } else {
      ElMessage.error(res.data.msg)
    }
  })
}

const onSubmits = () => {
  router.push("/MianView")
}

//#endregion

</script>

<style scoped>
.captcha {
  cursor: pointer;
}

.parent {
  display: flex;
  justify-content: center;
  /* 水平居中 */
  align-items: center;
  /* 垂直居中 */
  height: 100vh;
  /* 设置父元素高度为视口高度 */
}

.child {
  background-color: #f0f0f0;
  padding: 70px;
}
</style>